﻿using AuthCenter.Api.Read.Application.Command.Menu;
using AuthCenter.Api.Read.Application.Output;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace AuthCenter.Api.Read.Application.Hander.Menu
{
    public class GetMenuShowHander : IRequestHandler<GetMenuShowCommand, ApiResult<List<MenuOutput>>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IMapper _mapper;
        public GetMenuShowHander(IBaseRepository<MenuModel> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        public Task<ApiResult<List<MenuOutput>>> Handle(GetMenuShowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<MenuOutput>> res=new ApiResult<List<MenuOutput>>();
            var model = _menuRepository.GetAll().OrderByDescending(x => x.Id).Where(x => x.IsDeleted == false);
            var models = _menuRepository.GetAll().OrderByDescending(x => x.Id).Where(x => x.IsDeleted == false);
            var linq = (from a in model
                        join b in models on a.PId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        select new MenuOutput
                        {
                            Id = a.Id,
                            MenuName = a.MenuName,
                            PId = a.PId,
                            Sorting = a.Sorting,
                            Url = a.Url,
                            CreateBy = a.CreateBy,
                            CreateTime = a.CreateTime,
                            UpdateTime = a.UpdateTime,
                            UpdateBy = a.UpdateBy,
                            PName = b.MenuName

                        }).ToList();
            res.Code = ApiEnums.OK;
            res.Message = "查询成功";
            res.Data = linq.ToList();
            return Task.FromResult(res);
        }
    }
}
